﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using DocumentGain.model;
using DocumentGain;
using DocumentGain.dal;
using System.Configuration;
using System.Threading;
using Ican.YunPan.Services;
using Ican.YunPan.Services.GridFS;

namespace DocumentGain
{
    public partial class Leading_关注 : Form
    {

        string connstr = ConfigurationManager.AppSettings["MongoConnectionString"];
        string dbName = ConfigurationManager.AppSettings["MongoDBName"];
        string FilePath = ConfigurationManager.AppSettings["FilePath"];

        string cutTime = ConfigurationManager.AppSettings["cutTime"];
        string iscutTimebefore = ConfigurationManager.AppSettings["iscutTimebefore"];


        private delegate void SetControlTextCallback(Control o, string text);
        Service service = new Service();
        private string _allmessage = "";
        string LogDate = "";

        string nr = "";
        public Leading_关注()
        {
            InitializeComponent();
        }

        public void DataLeadingin(object o)
        {

            string delsql = @"delete from mp_focus";
            sqlHelpIcanYunPan.ExecuteSql(delsql); 

            MessageShow("开始导入关注数据");
            string sql = "select TakeCareID,DocumentID,strName,TakeCareTime from TakeCare";
            DataTable dt = sqlHelp.Query(sql).Tables[0];
            WriteLogFile("有" + dt.Rows.Count + "条数据待导入");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                MessageShow("开始导入" + i.ToString() + "条数据");
                MP_Focus mp_focus = new MP_Focus();
                mp_focus.Id = Guid.NewGuid();

                string sql1 = @"select Id,InstanceId,Title,MPListId,TableName from View_WorkFlow_Sc where InstanceId in (
select InstanceId from MP_DocumentID where DocumentID = '" + dt.Rows[i]["DocumentID"].ToString() + "')";
                DataTable dt1 = sqlHelpIcanYunPan.Query(sql1).Tables[0];
                if (dt1.Rows.Count > 1)
                {
                    mp_focus.FormId = dt1.Rows[0]["MPListId"].ToString(); ;
                    mp_focus.FormCode = dt1.Rows[0]["TableName"].ToString();
                    mp_focus.DataId = dt1.Rows[0]["Id"].ToString();
                    mp_focus.InstanceId = dt1.Rows[0]["InstanceId"].ToString();
                    mp_focus.CreatedDate = Convert.ToDateTime(dt.Rows[i]["TakeCareTime"].ToString().Replace("UTC+0800", "").Trim());
                    string UserName = dt.Rows[i]["strName"].ToString();
                    string sql2 = @"select Id from YP_User where Alias in (select LoginName from UserRelation where UserName = '" + UserName + "')";
                    DataTable dt2 = sqlHelpIcanYunPan.Query(sql2).Tables[0];
                    if (dt2.Rows.Count > 0)
                    {
                        mp_focus.CreatedBy = dt2.Rows[0]["Id"].ToString();
                    }
                    string sql3 = @"select flowtype,TableName,WorkflowName,WorkflowPackage,WorkflowTitle,MPListId from FlowTypeCorrelation where flowtype in (
select flowtype from MainDocument where DocumentID = '" + dt.Rows[i]["DocumentID"] + "')";
                    DataTable dt3 = sqlHelp.Query(sql3).Tables[0];
                    if (dt3.Rows.Count > 0)
                    {
                        mp_focus.WorkflowName = dt3.Rows[0]["WorkflowName"].ToString();
                        mp_focus.WorkflowPackage = dt3.Rows[0]["WorkflowPackage"].ToString();
                    }

                    mp_focus.OriginatorId = "";
                    mp_focus.OriginatorName = "";
                    mp_focus.AttachmentIds = "0";
                    try
                    {
                        string strTemp = string.Format("select AttachmentIds from {0} where id = '{1}'", mp_focus.FormCode, mp_focus.DataId);
                        DataSet dsTemp = sqlHelpIcanYunPan.Query(strTemp);
                        if (dsTemp != null && dsTemp.Tables[0].Rows.Count > 0)
                        {
                            mp_focus.AttachmentIds = dsTemp.Tables[0].Rows[0][0].ToString();
                        }
                    }
                    catch
                    { 
                        
                    }
                    string strTemp1 = string.Format("select [User] from Auditing where DocumentID = '{0}' order by date", dt.Rows[i]["DocumentID"].ToString());
                    DataSet dsTemp1 = sqlHelp.Query(strTemp1);
                    if (dsTemp1 != null && dsTemp1.Tables[0].Rows.Count > 0)
                    {
                        mp_focus.OriginatorName = dsTemp1.Tables[0].Rows[0][0].ToString().Replace("/whdt", "");
                        try
                        {
                            string sql4 = @"select Id from YP_User where Alias in (select LoginName from UserRelation where UserName = '" + mp_focus.OriginatorName + "')";
                            DataTable dt4 = sqlHelpIcanYunPan.Query(sql4).Tables[0];
                            mp_focus.OriginatorId = dt4.Rows[0]["Id"].ToString();
                        }
                        catch
                        {

                        }
                    }

                    if (mp_focus.FormCode == "BD_119_部门会签")
                    {
                        mp_focus.WorkflowName = "WHRT_BMHQ";
                        mp_focus.WorkflowPackage = "WHRT_HQ";
                        mp_focus.FormId = "596448eec2dfd680f81d1f33";
                    }

                    mp_focus.History = "1";

                    if (mp_focus.OriginatorId == "")
                    {
                        string sql11 = "select Id,[Name] from YP_User where [Name] = '" + mp_focus.OriginatorName + "'";
                        DataTable dt11 = sqlHelpIcanYunPan.Query(sql11).Tables[0];

                        if (dt11.Rows.Count == 1)
                        {
                            mp_focus.OriginatorId = dt11.Rows[0]["Id"].ToString();
                        }
                    }

                    service.AddMP_Focus(mp_focus);

                    if (mp_focus.FormCode == "BD_119_部门会签")
                    {
                        string title = "";

                        string sql0 = @"select Title from View_WorkFlow_Sc where InstanceId in (
select PInstanceId from BD_119_部门会签 where InstanceId = '" + dt1.Rows[0]["InstanceId"].ToString() + "')";
                        DataTable dt0 = sqlHelpIcanYunPan.Query(sql0).Tables[0];
                        if (dt0.Rows.Count > 0)
                        {
                            title = dt0.Rows[0]["Title"].ToString();
                        }

                        string sqlupdate = @"update mp_focus set title = '" + title + "',BussinessType = '部门会签' where Id = '" + mp_focus.Id + "'";
                        sqlHelpIcanYunPan.ExecuteSql(sqlupdate);
                    }
                    else
                    {
                        string sqlupdate = @"update mp_focus set title = '" + dt1.Rows[0]["Title"].ToString() + "',BussinessType = '" + dt3.Rows[0]["flowtype"].ToString() + "' where Id = '" + mp_focus.Id + "'";
                        sqlHelpIcanYunPan.ExecuteSql(sqlupdate);
                    }

                    string sqldel = "delete TakeCare where TakeCareID = '" + dt.Rows[i]["TakeCareID"].ToString() + "'";
                    sqlHelp.ExecuteSql(sqldel);
                    
                }

            }
            MessageShow("导入完成");
        }


        private void button1_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(DataLeadingin);
        }



        public void MessageShow(String input)
        {
            SetControlText(this.textBox1, input);
        }

        //写入文本日志
        public void WriteLogFile(String input)
        {
            SetControlText(this.textBox1, input);

            //指定日志文件的目录
            string fname = ConfigurationManager.AppSettings["LogPath"];

            //定义文件信息对象 
            FileInfo finfo = new FileInfo(fname + "Leading_PublicDoc" + DateTime.Now.ToString("yyyyMMdd") + ".txt");

            //判断文件是否存在以及是否大于2K 
            if (finfo.Exists && finfo.Length > 20480000)
            {
                //删除该文件 
                finfo.Delete();
            }
            //创建只写文件流 
            using (FileStream fs = finfo.OpenWrite())
            {
                //根据上面创建的文件流创建写数据流 
                StreamWriter w = new StreamWriter(fs);
                //设置写数据流的起始位置为文件流的末尾 
                w.BaseStream.Seek(0, SeekOrigin.End);

                w.Write("\r\n ");

                //写入日志内容并换行 
                w.Write(input + "\n ");
                //w.Write("--\n ");
                //清空缓冲区内容，并把缓冲区内容写入基础流 
                w.Flush();
                //关闭写数据流 
                w.Close();
            }
        }
        private void SetControlText(Control o, string text)
        {
            try
            {
                if (o.InvokeRequired)
                {
                    SetControlTextCallback d = new SetControlTextCallback(SetControlText);
                    this.Invoke(d, o, text);
                }
                else
                {
                    _allmessage = text + "\r\n" + _allmessage;
                    o.Text = _allmessage;
                }
            }
            catch { }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(DataLeadingin);
        }
    }
}
